package firewalla

import (
	"net"
	"os"
	"os/exec"

	"github.com/nextdns/nextdns/config"
	"github.com/nextdns/nextdns/router/internal"
)

type Router struct {
	DNSMasqPath     string
	ListenPort      string
	ClientReporting bool
}

func New() (*Router, bool) {
	if _, err := os.Stat("/etc/firewalla_release"); err != nil {
		return nil, false
	}
	return &Router{
		DNSMasqPath: "/home/pi/.firewalla/config/dnsmasq_local/nextdns.conf",
		ListenPort:  "5342",
	}, true
}

func (r *Router) Configure(c *config.Config) error {
	c.Listens = []string{net.JoinHostPort("localhost", r.ListenPort)}
	r.ClientReporting = c.ReportClientInfo
	if c.CacheSize == "0" || c.CacheSize == "" {
		// Make sure we setup a non-0 cache as we disable dnsmasq cache
		c.CacheSize = "10MB"
	}
	return nil
}

func (r *Router) Setup() error {
	return r.setupDNSMasq()
}

func (r *Router) Restore() error {
	if err := os.Remove(r.DNSMasqPath); err != nil {
		return err
	}
	return restartDNSMasq()
}

func (r *Router) setupDNSMasq() error {
	if err := internal.WriteTemplate(r.DNSMasqPath, tmpl, r, 0644); err != nil {
		return err
	}
	return restartDNSMasq()
}

func restartDNSMasq() error {
	return exec.Command("systemctl", "restart", "firerouter_dns.service").Run()
}

var tmpl = `# Configuration generated by NextDNS
no-resolv
server=127.0.0.1#{{.ListenPort}}
add-mac
add-subnet=32,128
max-cache-ttl=0
`
